var selectedRow = '';
var isModel = 1;

$(function (){
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openCheckDiaryPage('info');
        },
    };
    regValidate(["#checkDiaryForm"]);
    laydate.render({
        elem: '#diaryDate'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    var now = new Date();
    var date = new Date(now.getTime() + 7 * 24 * 3600 * 1000);
    laydate.render({
        elem: '#topTime'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        ,value: dateFtt("yyyy-MM-dd", now) + " 00:00:00"+ ' - ' + dateFtt("yyyy-MM-dd", date) + " 00:00:00"
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    $("#imgDiv").hide();
    var value = $("input[name=isTop]:checked").val();
    if(value == 'Y'){
        $("#topDiv").show();
    }else{
        $("#topDiv").hide();
    }

    $("input[name=isTop]").click(function(){
        changeDiv();
    });

});

//通用名称
function formatName(value, row, index) {
    if (!value || value == '') {
        return '<p class="infoView" >暂无内容</p>';
    }
    return '<p class="infoView" >'+value+'</p>';
}


function formatMood(str){
    return '<div class=\"gallerys\"><img src="'+ basePath + 'images/common/'+ str +'.png" style="width: 50px;height: 50px;" onerror="whenError(this)" class="gallery-pic" ></div>';
}

function formatTime(value, row, index){
    if(value){
        return value.substr(0,value.length-3);
    }
    return '';
}

function doRefresh() {
    var value = $("#hiddenMood").val();
    if(value == 'undefined'|| value == undefined){
        value = '';
    }
    selectedRow = '';
    var userId = $("#userId").val();
    var contents = $("#contents").val();
    var diaryStartTimeStr;
    var diaryEndTimeStr;
    var timeInterval = $("#diaryDate").val();
    if(value != ''){
        $("#inputDiv").hide();
        $("#imgDiv").show();
        $("#moodImg").attr('src',basePath + 'images/common/'+ value +'.png');
    }

    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            diaryStartTimeStr = dates[0];
            diaryEndTimeStr = dates[1];
        }
    }

    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'checkMoodDiary/pageFindDiaryCheckData?t=' + new Date().getTime(),
        query: {
            userId : userId,
            mood : value,
            contents : contents,
            diaryStartTimeStr : diaryStartTimeStr,
            diaryEndTimeStr : diaryEndTimeStr,
        },
    });
}

function changeDiv(){
    var value = $("input[name=isTop]:checked").val();
    if(value == 'Y'){
        $("#topDiv").show();
    }else{
        $("#topDiv").hide();
    }
}

function doReset(){
    $("#userId").val('');
    //****************重置表情****************************
    $("#inputDiv").show();
    $("#imgDiv").hide();
    $("#hiddenMood").val('');
    $("#moodImg").attr('src','');

    $("#hiddenMood").val('');
    $("#contents").val('');
    $("#diaryDate").val('');
}

$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRow = row;
});

function openCheckDiaryPage(type){
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if(selectedRow.exoteric != 'Y' && type != 'info'){
        toastr.error("非公开的日记无需审核");
        return;
    }
    var postData = {
        id : selectedRow.id,
        userId : selectedRow.userId,
    };
    var url = basePath + 'checkMoodDiary/openMoodDiaryPage?type='+type+'&t=' + new Date().getTime();
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: postData,
        success : function (data) {
            if(data && data.result){
                showCheckDiaryPage(data.content)
            }else if(data&&!data.result){
                toastr.error(data.message);
            }else{
                toastr.error('查询心情日记信息失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function selectMood(value){
    $("#hiddenMood").val(value);
    doRefresh();
}

function showCheckDiaryPage(content){
    if (content) {
        $("input[name=isTop]:eq(0)").prop("checked", true);
        $("#topDiv").hide();
        $('#lab_userId').html(content.userId);
        $('#lab_mood').html('');
        $('#lab_habitName').html('');
        var picDiv = '<div class=\"gallerys\"><img src="'+ basePath + '/images/common/'+ content.mood +'.png" style="width: 40px;height: 40px;" onerror="whenError(this)" class="gallery-pic" ></div>';
        $('#lab_mood').append(picDiv);
        //var habits = content.habits.
        $('#lab_habitName').html(content.habitName);
        $('#lab_contents').html(content.contents);
        var div = '';
        $("#picDiv").html('');
        var picList = content.picList;
        if(picList && picList.length > 0){
            $.each(picList,function(index,value){
                div += '<img style="float:left;width: 180px;height: 150px" id="coverUrlImg" onclick="$.openPhotoGallery(this)" src="'+ value +'" class="img-rounded win-img gallery-pic">';
            });
            if (content.contents && content.contents != '') {
                isModel = 2;
            } else {
                isModel = 1;
            }
        } else {
            isModel = 1;
        }
        $("#picDiv").append(div);
    }
    $('#checkDiary').modal(true);
}

function checkPassBtn(){
    // var str = '确定通过审核吗？';
    //         swalToastr('审核通过', str, 'warning', doCheckDiary, '确定');
    // hideLoading();
    $('#topTime').val('');
    $('#topSort').val('');
    if (isModel == 1) {
        $('#score').val('1');
    } else {
        $('#score').val('2');
    }
    $('#checkPassDiary').modal(true);
}

function unCheckPassBtn(){
    $('#unCheckPassDiary').modal(true);
}

function doUnCheckPassDiary(){
    var reason = $.trim($("#error_textarea").val());
    if(reason == null || reason == ''){
        toastr.error('请输入审核不通过原因');
        return;
    }
    var postData = {};
    postData.id = selectedRow.id;
    postData.userId = selectedRow.userId;
    postData.reason = reason;
    postData.isTop = '';
    $.ajax({
        type: 'post',
        url: basePath +  'checkMoodDiary/unCheckPassDiary',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        success : function (data) {
            if(data.result){
                //toastr.success(data.message);
                //window.location.href = basePath + 'checkMoodDiary/moodDiaryPage?t=' + new Date().getTime();
                $('#checkDiary').modal("hide");
                $("#unCheckPassDiary").modal("hide");
                doRefresh();
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doCheckDiary(){
    if(!$("#checkDiaryForm").valid()) return;//校验不通过
    var score = $('#score').val();
    if (score == '') {
        toastr.error('请输入健康币奖励');
        return;
    }
    if (score < 1 || score > 10) {
        toastr.error('健康币奖励范围：1~10');
        return;
    }
    var isTop = $("input[name=isTop]:checked").val();
    var topTimeStr = "";
    var topSort = "";
    var topStarttime = "";
    var topEndtime = "";
    if(isTop == 'Y'){
        topTimeStr = $("#topTime").val();
        topSort = $("#topSort").val();
        if(topSort == null || topSort == ''){
            topSort = 999;
        }
        if(topTimeStr){
            var dates = topTimeStr.split(' - ');
            if(dates && dates.length >1){
                topStarttime = dates[0];
                topEndtime = dates[1];
            }
        }
        if(judgementDate(topStarttime,topEndtime) <= 0){
            toastr.error('置顶开始时间必须小于置顶结束时间 ');
            return;
        }
    }
    $.ajax({
        type: 'post',
        url: basePath + 'checkMoodDiary/checkPassDiary',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            id : selectedRow.id,
            userId : selectedRow.userId,
            isTop : isTop,
            topStarttime : topStarttime,
            topEndtime : topEndtime,
            topSort : topSort,
            score : score,
        }),
        success: function (data) {
            hideLoading();
            if (data.result) {
                //window.location.href = basePath + 'checkMoodDiary/moodDiaryPage?t=' + new Date().getTime();
                $('#checkDiary').modal("hide");
                $("#checkPassDiary").modal("hide");
                doRefresh();
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            hideLoading();
            toastr.error(common_system_error);
        }
    });
}

